package com.paho.config;

import com.paho.anno.MqttListener;
import com.paho.handler.MqttDistribute;
import com.paho.handler.MqttHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Map;

/**
 *  SpringBoot项目启动时,将加了@MqttListener注解的类,注册到分发处理器MqttDistribute中
 * @Author wdy
 * @Date 2023/9/19
 **/
@Component
@Slf4j
public class MqttApplicationContext implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        MqttDistribute distribute = applicationContext.getBean(MqttDistribute.class);
        if (ObjectUtils.isEmpty(distribute)) {
            log.error("mqtt消息分发器不存在------------------------------------");
            return;
        }

        Map<String, MqttHandler> beans = applicationContext.getBeansOfType(MqttHandler.class);
        beans.forEach((key, value) -> {
            boolean present = value.getClass().isAnnotationPresent(MqttListener.class);
            if (present) {
                MqttListener mqttListener = value.getClass().getAnnotation(MqttListener.class);
                String topic = mqttListener.value();
                // 订阅主题
                distribute.putHandlerBean(topic, value);
            }
        });


    }
}
